package top.heliming.youyou.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.heliming.youyou.common.utils.CookieUtils;
import top.heliming.youyou.entity.UserInfo;
import top.heliming.youyou.properties.JwtProperties;
import top.heliming.youyou.service.AuthService;
import top.heliming.youyou.util.JwtUtils;

/**
 * description: //TODO
 *
 * @author: heliming
 * @date:2019/06/09 下午 12:55
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

  @Autowired
  private AuthService authService;

  @Autowired
  private JwtProperties prop;

  /**
   * 登录授权
   *
   * @param username
   * @param password
   * @return
   */
  @PostMapping("accredit")
  public ResponseEntity<Void> authentication(
      @RequestParam("username") String username,
      @RequestParam("password") String password,
      HttpServletRequest request,
      HttpServletResponse response) {
    // 登录校验
    String token = this.authService.authentication(username, password);
    if (StringUtils.isBlank(token)) {
      return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    }
    // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
    CookieUtils.newBuilder(response).httpOnly().maxAge(prop.getCookieMaxAge()).request(request).build(prop.getCookieName(), token);
    return ResponseEntity.ok().build();
  }

  /**
   * 验证用户信息
   * @param token
   * @return
   */
  @GetMapping("verify")
  public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN")String token, HttpServletRequest request, HttpServletResponse response){
    try {
      // 从token中解析token信息
      UserInfo userInfo = JwtUtils.getUserInfo( this.prop.getPublicKey(),token);
      //成功，刷新Token
      String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
      //将新的Token写入cookie中，并设置httpOnly
      CookieUtils.newBuilder(response).httpOnly().maxAge(prop.getCookieMaxAge()).request(request).build(prop.getCookieName(), newToken);
      // 解析成功返回用户信息
      return ResponseEntity.ok(userInfo);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // 出现异常则，响应500
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
  }
}